package com.eightbears.beboy.ui.user.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.cache.GroupMemberCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.popupwindow.MessageAddPopup;
import com.eightbears.beboy.base.view.qrcode.utils.CodeUtils;
import com.eightbears.beboy.base.view.qrcode.view.CaptureActivity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.base.PreferenceManager;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.beboy.ui.chat.ui.activity.GroupPickContactsActivity;
import com.eightbears.beboy.ui.chat.ui.fragment.EaseConversationListFragment;
import com.eightbears.beboy.ui.user.activity.AddContactActivity;
import com.eightbears.beboy.ui.user.activity.ContactsListActivity;
import com.eightbears.beboy.ui.user.activity.NeartyPeopleActivity;
import com.eightbears.beboy.ui.user.activity.SystemMessageActivity;
import com.eightbears.beboy.ui.user.activity.SystemMessageCommonActivity;
import com.eightbears.beboy.ui.user.activity.UserInfoActivity;
import com.eightbears.beboy.ui.user.activity.UserReserveActivity;
import com.eightbears.greendao.GroupList;
import com.eightbears.greendao.GroupMember;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.util.NetUtils;
import com.socks.library.KLog;

import java.util.ArrayList;

import butterknife.OnClick;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.MESSAGE_TYPE_RESERVATION;
import static com.eightbears.beboy.base.util.CommonAPI.MESSAGE_TYPE_SYSTEM;
import static com.eightbears.beboy.base.util.CommonAPI.MESSAGE_TYPE_SYSTEM_COMMENT;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATE_GROUP_ICON;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;
import static com.hyphenate.easeui.EaseConstant.CHATTYPE_GROUP;
import static com.hyphenate.easeui.EaseConstant.EXTRA_CHAT_TYPE;

public class MessageFragment extends EaseConversationListFragment {

    private static final int RESULT_CODE_QC = 0x001;
    private static final int RESULT_CREATE_GROUP = 0x002;
    public static final String PARAMS_QC_PAY_CODE = "shopPayCode";

    private TextView errorText;
    private View errorView;
    private TextView tv_title;
    private LinearLayout ll_right;
    private UserEntity mUserEntity;
    private MessageAddPopup messageAddPopup;

    private EMGroup emGroup;
    private View mView_top;

    @Override
    protected void initView() {
        super.initView();
        mUserEntity = SPUtil.getUser();

        if (mUserEntity.getData().getVip_level() == 2 && mUserEntity.getData() != null) {
            mRl_near.setVisibility(View.VISIBLE);
        } else {
            mRl_near.setVisibility(View.GONE);
        }
        errorView = View.inflate(getActivity(), R.layout.em_chat_neterror_item, null);
        errorItemContainer.addView(errorView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
        tv_title = (TextView) getActivity().findViewById(R.id.tv_title);
        ll_right = (LinearLayout) getActivity().findViewById(R.id.ll_right);
        mView_top = (View) getActivity().findViewById(R.id.view_top);
    }

    @Override
    protected void setUpView() {
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();

                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // 被评论
                    if (username.equals(MESSAGE_TYPE_SYSTEM_COMMENT)) {
                        Intent intent = new Intent(getActivity(), SystemMessageCommonActivity.class);
                        intent.putExtra(CommonAPI.EXTRA_USER_ID, username);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                        return;
                    }

                    if (username.equals(MESSAGE_TYPE_SYSTEM)) {

                        Intent intent = new Intent(getActivity(), SystemMessageActivity.class);
                        intent.putExtra(CommonAPI.EXTRA_USER_ID, username);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                        return;
                    }

                    if (username.equals(MESSAGE_TYPE_RESERVATION)) {
                        Intent intent = new Intent(getActivity(), UserReserveActivity.class);
                        intent.putExtra(CommonAPI.EXTRA_USER_ID, username);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                        return;
                    }

                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            intent.putExtra(CommonAPI.EXTRA_CHAT_TYPE, CommonAPI.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(CommonAPI.EXTRA_CHAT_TYPE, CommonAPI.CHATTYPE_GROUP);
                        }
                    }

                    intent.putExtra(CommonAPI.EXTRA_USER_ID, username);
                    intent.putExtra(EaseConstant.EXTAR_POSITION, position);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                }
            }
        });

        super.setUpView();
        initData();
        initEvent();
    }


    private void initData() {
        tv_title.setText(getText(R.string.menu_text_message));
    }

    private void initEvent() {
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginChatServer();

            }
        });

        ll_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == messageAddPopup) {
                    messageAddPopup = new MessageAddPopup(getActivity());
                    messageAddPopup.setOnClickItemListener(new MessageAddPopup.OnClickItemListener() {
                        @Override
                        public void onClickItem(String Type) {
                            switch (Type) {
                                case MessageAddPopup.ITEM_ADD_FRIEND:
                                    startActivity(new Intent(getActivity(), AddContactActivity.class));
                                    getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                                    break;
                                case MessageAddPopup.ITEM_CREATE_GROUP:
                                    startActivityForResult(
                                            new Intent(getActivity(), GroupPickContactsActivity.class)
                                                    .putExtra("groupName", mUserEntity.getData().getNickname() + "的群")
                                                    .putExtra("members", new ArrayList<>()), RESULT_CREATE_GROUP);
                                    break;
                                case MessageAddPopup.ITEM_QC_CODE:
                                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                                    startActivityForResult(intent, RESULT_CODE_QC);
                                    getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                                    break;
                            }

                            messageAddPopup.dismiss();
                        }
                    });
                }
                messageAddPopup.showDropDown(mView_top);
            }
        });

        mRl_near.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), NeartyPeopleActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        });
    }

    @OnClick(R.id.iv_friend_contact)
    void friendList() {
        iv_unread.setVisibility(View.GONE);
        startActivity(new Intent(getActivity(), ContactsListActivity.class));
        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())) {
            errorText.setText(R.string.can_not_connect_chat_server_connection);
        } else {
            errorText.setText(R.string.the_current_network);
        }
    }

    private void loginChatServer() {
        String username = mUserEntity.getData().getUser_id();
        String password = mUserEntity.getData().getChatPass();
        EMClient.getInstance().login(username, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                PreferenceManager.getInstance().setCurrentUserNick(mUserEntity.getData().getNickname());
                PreferenceManager.getInstance().setCurrentUserAvatar(mUserEntity.getData().getCover());
            }

            @Override
            public void onProgress(int progress, String status) {
                KLog.e(progress + "/" + status);
            }

            @Override
            public void onError(int code, String message) {
                ShowToast.showShortToast(getString(R.string.alert_connection_chat_fail));
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE_QC:
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            if (result.contains("beboy://friend/")) {
                                result = result.substring(result.lastIndexOf("/") + 1, result.length());
                                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                                intent.putExtra(PARAMS_USER_INFO, result);
                                startActivity(intent);
                                getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                            } else if (result.contains("http://beboy.me/invite")) {
                                //通过浏览器打开URL
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setData(Uri.parse(result));    //splitflowurl为分流地址
                                if (!CommonUtils.hasPreferredApplication(getActivity(), intent)) {
                                    intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
                                }
                                startActivity(intent);
                            }

                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            ShowToast.showShortToast("二维码解析失败");
                        }
                    }
                    break;

                case RESULT_CREATE_GROUP:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final String groupName = mUserEntity.getData().getNickname() + "的群";
                            String[] members = data.getStringArrayExtra("newmembers");
                            try {
                                EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
                                option.maxUsers = 200;
                                String reason = getString(R.string.invite_join_group);
                                reason = EMClient.getInstance().getCurrentUser() + reason + groupName;
                                option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
                                emGroup = EMClient.getInstance().groupManager().createGroup(groupName, " ", members, reason, option);
                                addGroup();
                            } catch (final Exception e) {
                                String st2 = getResources().getString(R.string.Failed_to_create_groups);
                                Toast.makeText(getContext(), st2 + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                    }).start();
                    break;
            }
        }
    }

    public void addGroup() {
        OkHttpUtils.post().url(URL_UPDATE_GROUP_ICON)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("group_id", emGroup.getGroupId())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                if (response.contains(CONNECTION_STATUS_SUCCESS)) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            GroupCache.getInstance(getContext()).saveData(new GroupList(emGroup.getGroupId(), "", emGroup.getGroupName()));
                            GroupMemberCache.getInstance(getContext()).saveData(new GroupMember(emGroup.getGroupId(), mUserEntity.getData().getUser_id() + ""));
                            Intent intent = new Intent(getActivity(), ChatActivity.class);
                            intent.putExtra(EXTRA_CHAT_TYPE, CHATTYPE_GROUP);
                            intent.putExtra("userId", emGroup.getGroupId());
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }

        });
    }
}
